import Cookie from 'js-cookie'
export default {
  state: {
    //状态
    menu: [],
    //点击的这个菜单
    currentMenu: null,
    //折叠
    isCollapse:false,
    //存放tablist
    tabList: [{
        path: '/',
        name: 'home',
        lable: '首页',
        icon:'home'
    }]
  },
  mutations: {
    //保存菜单的方法
    setMenu(state, val) { 
      state.menu = val
      //这里cookie只能存字符串，对象通过字符串的序列化
      Cookie.set('menu', JSON.stringify(val))
    },
    //清除菜单 退出登录清除cookie数据
    clearMenu(state) { 
      state.menu = []
      Cookie.remove('menu')
    },
    //动态添加
    addMenu(state, router) { 
      if (!Cookie.get('menu')) {
        return
      }
      let menu = JSON.parse(Cookie.get('menu'))
      state.menu = menu
      let currentMenu = [
        {
          path: '/',
          component: () => import('../views/Main.vue'),
          children: []
        }
      ]
      menu.forEach(item => {
        if (item.children) {
          item.children = item.children.map(item => { 
            item.component = () => import(`../views/${item.url}`)
            return item
          })
          currentMenu[0].children.push(...item.children)
        } else { 
          item.component = () => import(`../views/${item.url}`)
          currentMenu[0].children.push(item)
        }
      })
      console.log(currentMenu,'cur');
      //追加动态路由操作
      router.addRoutes(currentMenu)
    },
    //选择了这个菜单
    selectMenu(state, val) { 
      // state.currentMenu = val
      if (val.name !== 'home') {
        state.currentMenu = val
        //防止用户多次点击重复页面使得显示出同一一面的地址多次显示因此做去重
        let resule = state.tabList.findIndex(item => item.name === val.name)
        //如果是-1的话没找到就将点击的名字放进来 如果有就不进行任何操作
        resule === -1 ? state.tabList.push(val) : ''
      }else { 
        state.currentMenu = null
      }
    },
    closeTab(state, val) { 
      let result = state.tabList.findIndex(item => item.name === val.name)
      state.tabList.splice(result, 1)
    },
    //收缩展开作用
    collapseMenu(state) { 
      state.isCollapse = !state.isCollapse
    }
  },
  actions: {},
}